import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'product_detail_logic.dart';
import '../../../gen/assets.gen.dart';

/// 商品详情页面
class ProductDetailView extends StatefulWidget {
  const ProductDetailView({super.key});

  @override
  State<ProductDetailView> createState() => _ProductDetailViewState();
}

class _ProductDetailViewState extends State<ProductDetailView> {
  final controller = Get.find<ProductDetailLogic>();

  // 简单的HTML标签移除
  String _stripHtmlTags(String htmlString) {
    return htmlString
        .replaceAll(RegExp(r'<[^>]*>'), '')
        .replaceAll('&nbsp;', ' ')
        .replaceAll('&amp;', '&')
        .replaceAll('&lt;', '<')
        .replaceAll('&gt;', '>')
        .trim();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF1C1C1E),
      body: Obx(() {
        final product = controller.state.productDetail.value;
        if (product == null) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        return Column(
          children: [
            // 顶部导航栏
            SafeArea(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () => Get.back(),
                      child: Icon(
                        Icons.arrow_back_ios,
                        color: Colors.white,
                        size: 20.sp,
                      ),
                    ),
                    Expanded(
                      child: Text(
                        '商品详情',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 18.sp,
                          fontWeight: FontWeight.w600,
                          color: Colors.white,
                        ),
                      ),
                    ),
                    SizedBox(width: 20.w), // 占位，保持标题居中
                  ],
                ),
              ),
            ),
            // 可滚动内容
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 图片轮播
                    _buildImageCarousel(),
                    SizedBox(height: 24.h),
                    // 商品信息
                    _buildProductInfo(product),
                    SizedBox(height: 100.h), // 为底部按钮留出空间
                  ],
                ),
              ),
            ),
            // 底部兑换按钮
            _buildBottomButton(),
          ],
        );
      }),
    );
  }

  /// 图片轮播
  Widget _buildImageCarousel() {
    return Obx(() {
      final imageUrls = controller.state.imageUrls;
      
      if (imageUrls.isEmpty) {
        return Container(
          height: 300.h,
          margin: EdgeInsets.symmetric(horizontal: 20.w),
          decoration: BoxDecoration(
            color: Colors.grey[800],
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.image_not_supported,
                  size: 60.sp,
                  color: Colors.grey[600],
                ),
                SizedBox(height: 8.h),
                Text(
                  '暂无图片',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
        );
      }

      return SizedBox(
        height: 300.h,
        child: Stack(
          children: [
            PageView.builder(
              itemCount: imageUrls.length,
              onPageChanged: (index) {
                controller.state.currentImageIndex.value = index;
              },
              itemBuilder: (context, index) {
                return Container(
                  margin: EdgeInsets.symmetric(horizontal: 20.w),
                  decoration: BoxDecoration(
                    color: Colors.grey[800],
                    borderRadius: BorderRadius.circular(16.r),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(16.r),
                    child: Image.network(
                      imageUrls[index],
                      fit: BoxFit.cover,
                      loadingBuilder: (context, child, loadingProgress) {
                        if (loadingProgress == null) return child;
                        return Center(
                          child: CircularProgressIndicator(
                            value: loadingProgress.expectedTotalBytes != null
                                ? loadingProgress.cumulativeBytesLoaded /
                                    loadingProgress.expectedTotalBytes!
                                : null,
                          ),
                        );
                      },
                      errorBuilder: (context, error, stackTrace) {
                        return Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.broken_image,
                                size: 60.sp,
                                color: Colors.grey[600],
                              ),
                              SizedBox(height: 8.h),
                              Text(
                                '图片加载失败',
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  color: Colors.grey[600],
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                );
              },
            ),
            // 图片指示器
            if (imageUrls.length > 1)
              Positioned(
                bottom: 16.h,
                left: 0,
                right: 0,
                child: Obx(() => Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: List.generate(
                        imageUrls.length,
                        (index) => Container(
                          margin: EdgeInsets.symmetric(horizontal: 4.w),
                          width: 6.w,
                          height: 6.w,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: controller.state.currentImageIndex.value == index
                                ? Colors.white
                                : Colors.white.withOpacity(0.4),
                          ),
                        ),
                      ),
                    )),
              ),
          ],
        ),
      );
    });
  }

  /// 商品信息
  Widget _buildProductInfo(Map<String, dynamic> product) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 商品名称
          Text(
            product['name'] ?? '',
            style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 16.h),
          // 价格信息
          Row(
            children: [
              Row(
                children: [
                  Assets.points.dollar.image(
                    width: 20.w,
                    height: 20.w,
                  ),
                  SizedBox(width: 4.w),
                  Text(
                    '${product['pointsPrice']}',
                    style: TextStyle(
                      fontSize: 24.sp,
                      fontWeight: FontWeight.w700,
                      color: const Color(0xFFFFA726),
                    ),
                  ),
                  SizedBox(width: 4.w),
                  Text(
                    '积分',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ],
              ),
              SizedBox(width: 16.w),
              Text(
                '¥${product['originalPrice']}',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.grey[500],
                  decoration: TextDecoration.lineThrough,
                ),
              ),
            ],
          ),
          SizedBox(height: 16.h),
          // 库存信息
          Row(
            children: [
              Text(
                '库存: ${product['stockQuantity']}',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[400],
                ),
              ),
              SizedBox(width: 24.w),
              Text(
                '限购: ${product['maxPerUser']}件/人',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[400],
                ),
              ),
            ],
          ),
          SizedBox(height: 24.h),
          // 分隔线
          Container(
            height: 1,
            color: Colors.grey[800],
          ),
          SizedBox(height: 24.h),
          // 商品详情标题
          Text(
            '商品详情',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 12.h),
          // 商品描述
          Text(
            _stripHtmlTags(product['description'] ?? ''),
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey[300],
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  /// 底部兑换按钮
  Widget _buildBottomButton() {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: const Color(0xFF1C1C1E),
        border: Border(
          top: BorderSide(
            color: Colors.grey[800]!,
            width: 1,
          ),
        ),
      ),
      child: SafeArea(
        child: GestureDetector(
          onTap: controller.onExchange,
          child: Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(vertical: 16.h),
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                colors: [Color(0xFFFF6B35), Color(0xFFF46425)],
              ),
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Text(
              '立即兑换',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
